angular.module("chat.controllers", ['ui.bootstrap'])
    .controller('ChatController', ['$scope', '$uibModal', 'ChatService',
        function ($scope, $uibModal, chatService) {
            $scope.notifications = [];
            $scope.ms = [];
            //总是把最新通知放在数组中的前面
            var pushNotification = function (message) {
                $scope.notifications.unshift(message);
            };

            //定义退出方法
            $scope.logout = function () {
                chatService.disconnect();
            };
            $scope.sendTo=function(to){
                $scope.msg='@'+to+";";
            };
            $scope.sendMessage = function () {
                $scope.type='public'
                if($scope.msg.indexOf('@')==0){
                    $scope.type='private'
                    $scope.to=$scope.msg.substring(1,$scope.msg.indexOf(';'));
                }
                var m = {
                    from: $scope.userName,
                    type: $scope.type,
                    content: $scope.msg,
                    to: $scope.to
                };
                chatService.send(m);
            }
            //建立websocket链接
            chatService.connect('/mchat/mchat').then(function (m) {
                //成功
                pushNotification(m);
                $scope.userName = m;
            }, function (e) {
                //失败
                pushNotification(e);

            }).then(function (m) {
                chatService.welcome().then(
                    null, function (e) {

                        pushNotification(e);

                    }, function (m) {

                        pushNotification(e);

                    });
                chatService.room().then(null, function (e) {
                        pushNotification(e);

                    },
                    function (m) {
                        m.his = true;
                        $scope.ms.push(m);
                    });
                chatService.mine().then(null, function (e) {
                        pushNotification(e);
                    },
                    function (m) {
                        m.his = true;
                        $scope.ms.push(m);

                    }
                );
                chatService.error().then(null, function (e) {

                        pushNotification(e);

                    },
                    function (m) {
                        pushNotification(m);
                    }
                );

            }, function (e) {
                pushNotification(e);
            });
        }]);